package com.tjtt.tdm.form.service.impl;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.flow.bean.FlowDetailed;
import com.tjtt.tdm.flow.bean.FlowTask;
import com.tjtt.tdm.flow.bean.FlowTaskInfo;
import com.tjtt.tdm.flow.bean.TdmCustomNo;
import com.tjtt.tdm.form.bean.AutoFormsButton;
import com.tjtt.tdm.form.bean.AutoFormsField;
import com.tjtt.tdm.form.bean.AutoFormsNew;
import com.tjtt.tdm.form.dao.IAutoDao;
import com.tjtt.tdm.form.dao.IAutoFormDao;
import com.tjtt.tdm.form.service.IAutoFormService;

public class AutoFormServiceImpl implements IAutoFormService{
	
	private IAutoFormDao autoFormDao;
	private IAutoDao autoDao;
	
	public int insertCreateSequencesSql(String sequencesName) {
		return 0;
	}
	
	
	public int insertCreateTableSql(AutoFormsNew autoFormNew,String tableName) {
		autoFormDao.insertCreateTableSql(tableName);
		autoFormDao.insertCreateSequencesSql(tableName);
		String formsId = autoFormDao.saveAutoFormsNew(autoFormNew);
		AutoFormsField autoField = new AutoFormsField();
		autoField.setCnName("主键");
		autoField.setFieldName("ID");
		autoField.setFieldType("NUMBER");
		autoField.setIsReadOnly(1l);
		autoField.setIsListShow(1l);
		autoField.setIsPageShow(0l);
		autoField.setPageDisplayType(0l);
		autoField.setAuthenticationType("0");
		autoField.setFormsId(Long.parseLong(formsId));
		autoFormDao.saveAutoFormsField(autoField);
		return 0;
	}
	
	
	public String saveAutoFormsNew(AutoFormsNew autoFormNew) {
		return autoFormDao.saveAutoFormsNew(autoFormNew);
	}


	
	public PageResult queryAutoFormsListNew(Map filterMap) {
		return autoFormDao.queryAutoFormsListNew(filterMap);
	}
	public PageResult queryAutoFormsListNewData(Map filterMap) {
		return autoFormDao.queryAutoFormsListNewData(filterMap);
	}

	
	public void saveAutoFormsField(AutoFormsField autoFormsField) {
		autoFormDao.saveAutoFormsField(autoFormsField);
	}
	
	public IAutoFormDao getAutoFormDao() {
		return autoFormDao;
	}

	public void setAutoFormDao(IAutoFormDao autoFormDao) {
		this.autoFormDao = autoFormDao;
	}
	
	public List queryAutoFormListByFormEnName(String formEnName) {
		return autoFormDao.queryAutoFormListByFormEnName(formEnName);
	}
	
	public PageResult queryAutoFormsFieldListByFormId(Map filterMap) {
		return autoFormDao.queryAutoFormsFieldListByFormId(filterMap);
	}
	public PageResult queryAutoFormsFieldListDicByFormId(Map filterMap) {
		return autoFormDao.queryAutoFormsFieldListDicByFormId(filterMap);
	}
	
	public void deleteAutoFormById(String id) {
		autoFormDao.deleteAutoFormById(id);
	}
	
	
	public void deleteAutoFormFieldByFormId(String formId) {
		autoFormDao.deleteAutoFormFieldByFormId(formId);
	}
	
	
	public void deleteTableAndSeqAndDateByFormName(String tableName,
			String formId) {
		String queryFormIdSql = "select t.id from auto_forms_new t where t.form_en_name = '"+tableName+"'";
		List list = autoFormDao.getDatabySql(queryFormIdSql);
		//如果根据表名查询出的数据大于1条
		if(list.size() > 1){
			String deleteFieldSqlByFormId = "delete from auto_forms_field t where t.forms_id = "+formId;
			autoFormDao.executeSql(deleteFieldSqlByFormId);
			autoFormDao.deleteAutoFormById(formId);
		}else{
			//根据表名删除auto_forms_new里的数据
			String deleteFormByTableName = "delete from auto_forms_new t where t.form_en_name = '"+tableName+"'";
			autoFormDao.executeSql(deleteFormByTableName);
			autoFormDao.deleteAutoFormById(formId);
			autoFormDao.deleteAutoFormFieldByFormId(formId);
			autoFormDao.deleteTableAndSeqByFormName(tableName);
		}
	}
	
	
	public List getTableColumnAndCommentAndDataType(String tableName) {
		return autoFormDao.getTableColumnAndCommentAndDataType(tableName);
	}
	
	
	public AutoFormsNew getAutoFormsNewById(String formId) {
		return autoFormDao.getAutoFormsNewById(formId);
	}

	
	public List<AutoFormsField> getAutoFormsFieldByformid(String formid) {
		if (formid==null && formid.equals("")){
			return null;
		}
		return autoFormDao.getAutoFormsFieldByformid(formid);
	}
	
	/**
	 * 获取表单的数据
	 * author:lishu	 2014-1-9
	 */
	public List getAutoFormsFieldValues(String formid,String formName,String taskid){
		return autoFormDao.getAutoFormsFieldValues(formid,formName,taskid);
	}
	
	
	public void addFormFieldByTable(String tableName,
			AutoFormsField autoFormsField,String formId) {
		//根据表名查询出该表名有多少个表单
		String getFormByTableNameSql = "select t.id from auto_forms_new t where t.form_en_name = upper('"+tableName+"')";
		List formIdList = autoFormDao.getDatabySql(getFormByTableNameSql);
			//如果只有一个表单则直接插入数据（证明是新添加的表）
		if(formIdList.size() == 1){
			autoFormDao.saveAutoFormsField(autoFormsField);
			autoFormDao.addFormFieldByTable(tableName, autoFormsField);
		}else{
			//否则则是添加的已存在表，那么这个新添加的字段需要在所有表单里面都插入一边，默认页面显示状态为否
			for (int i = 0; i < formIdList.size(); i++) {
				//如果当前表单id等于页面传过来的id，则往这个表单中插入页面所填信息
				if(formId.equals(formIdList.get(i).toString())){
					autoFormDao.saveAutoFormsField(autoFormsField);
					autoFormDao.addFormFieldByTable(tableName, autoFormsField);
				}else{
					AutoFormsField aff = new AutoFormsField();
					aff.setCnName(autoFormsField.getCnName());
					aff.setFieldName(autoFormsField.getFieldName());
					aff.setPageDisplayType(autoFormsField.getPageDisplayType());
					aff.setPageDisplayType(0l);
					aff.setFormsId(Long.parseLong(formIdList.get(i).toString()));
					aff.setFieldNote(autoFormsField.getFieldNote());
					aff.setFieldType(autoFormsField.getFieldType());
					aff.setFieldLength(autoFormsField.getFieldLength());
					aff.setPageDisplayType(autoFormsField.getPageDisplayType());
					aff.setIsReadOnly(0l);
					aff.setIsListShow(0l);
					aff.setIsPageShow(0l);
					aff.setForeignTableId(autoFormsField.getForeignTableId());
					aff.setForeignCloumn(autoFormsField.getForeignCloumn());
					aff.setForeignDisCloumn(autoFormsField.getForeignDisCloumn());
					aff.setForeignTableName(autoFormsField.getForeignTableName());
					aff.setDefaultValue(autoFormsField.getDefaultValue());
					aff.setFitterCondition(autoFormsField.getFitterCondition());
					aff.setAuthenticationType("0");
					aff.setIsOrderBy(0l);
					autoFormDao.saveAutoFormsField(aff);
				}
			}
		}
	}
	
	
	public AutoFormsField getAutoFormFieldById(String id) {
		return autoFormDao.getAutoFormFieldById(id);
	}
	
	
	public void updateAutoFormField(AutoFormsField autoFormsField) {
		autoFormDao.updateAutoFormField(autoFormsField);
	}
	
	
	public void deleteAutoFormFieldBeanAndTableColumn(String fieldId,
			String tableName, String columnName) {
		//根据表名查询出该表名有多少个表单
		String getFormByTableNameSql = "select t.id from auto_forms_new t where t.form_en_name = upper('"+tableName+"')";
		List formIdList = autoFormDao.getDatabySql(getFormByTableNameSql);
		String formIds = "";
		for(int i = 0 ;i < formIdList.size(); i++){
			formIds += formIdList.get(i).toString() +",";
		}
		formIds = formIds.substring(0,formIds.length()-1);
		String deleteFormFieldSql = "delete from auto_forms_field t where t.field_name = upper('"+columnName+"') and t.forms_id in ("+formIds+")";
		autoFormDao.executeSql(deleteFormFieldSql);
		//autoFormDao.deleteAutoFormFieldById(fieldId);
		autoFormDao.deleteFormFieldByTableAndColumn(tableName, columnName);
	}
	
	public PageResult queryProjectTask(Map filterMap)
	{
		return autoFormDao.queryProjectTask(filterMap);
	}
	
	public void updateAutoForm(AutoFormsNew autoFormNew) {
		autoFormDao.updateAutoForm(autoFormNew);
	}
	
	
	public List getDatabySql(String sql) {
		return autoFormDao.getDatabySql(sql); 
	}
	
	
	public String executeSql(String sql) {
		return autoFormDao.executeSql(sql);
	}
	
	
	public PageResult queryAutoFormsButtonList(Map filterMap) {
		return autoFormDao.queryAutoFormsButtonList(filterMap);
	}
	
	
	public void saveAutoFormsButton(AutoFormsButton autoFormsButton) {
		autoFormDao.saveAutoFormsButton(autoFormsButton);
	}
	
	
	public void deleteAutoFormsButtonById(String ids) {
		String [] idss = ids.split(",");
		for (String id : idss) {
			autoFormDao.deleteAutoFormsButtonById(id);
		}
	}

	
	public void deleteFlowTaskById(String ids) {
		autoFormDao.deleteFlowTaskById(ids);
		autoFormDao.deleteFlowTaskInFoByFlowTaskId(ids);
	}

	
	public PageResult queryAutoFormsField(Map<String, String> filterMap) {
		return autoFormDao.queryAutoFormsField(filterMap);
	}

	
	public void removeView(String ids) {
		 autoFormDao.removeView(ids);
	}

	
	public FlowTask getFlowTaskById(Long ids) {
		return autoFormDao.getFlowTaskById(ids);
	}

	
	public void deleteFormTable(Long mainId, String formEnName) {
		autoFormDao.deleteFormTable(mainId,formEnName);
	}
	
	
	public AutoFormsButton getAutoFormButtonById(String id) {
		return autoFormDao.getAutoFormButtonById(id);
	}
	
	
	public void updateAutoFormButton(AutoFormsButton afb) {
		autoFormDao.updateAutoFormButton(afb);
	}

	/**
	 * 查询此表中是否存在此字段名称
	 * @author zhn
	 * @date Feb 17, 2014 2:27:16 PM
	 * @param fieldName
	 * @return
	 */
	public String findFieldName(String fieldName,String formId) {
		return autoFormDao.findFieldName(fieldName, formId);
	}

	
	public void insertDetailTable(String tableEnName) {
		autoFormDao.insertDetailTable(tableEnName);
	}

	
	public void insertTable(String formId,String tableCnName,String tableName,String formEnName) {
		autoFormDao.insertTable(tableName,formEnName);
		String auToFormNewId = "select SEQ_AUTO_FROMS.nextval from dual";
		String id = autoFormDao.queryNo(auToFormNewId);
		
		String auToFormNewSql = " insert into AUTO_FORMS_NEW  select "+id+",'"+tableCnName+"','"+tableName+"' ,t.form_path,t.form_note,t.form_column,t.form_format,t.create_name_id,t.create_name,t.create_time, "+
								" t.form_format_date,t.form_type,t.suoslx,t.form_width,t.form_height,t.iscaiji,t.caijiaddress,t.is_delete_table,t.column_cnname, "+
								" t.column_sql,t.column_width,t.column_forigen from AUTO_FORMS_NEW t where t.id="+formId+" ";
		autoFormDao.executeSql(auToFormNewSql);
		
		
		String auToFormFieldSql = " insert into AUTO_FORMS_FIELD   select SEQ_AUTO_FORMS_FIELD.nextval,t.cn_name,t.field_name,t.field_note,t.field_type,t.is_read_only,t.authentication_type,t.is_list_show,t.is_page_show, "+
								  " t.show_seq,t.is_column_merge,t.default_value,"+id+",t.is_query_field,t.field_length,t.field_list_width,t.is_order_by, "+
								  "	t.page_display_type,t.foreign_table_name,t.foreign_cloumn,t.foreign_dis_cloumn,t.foreign_table_id,t.fittercondition from AUTO_FORMS_FIELD t where t.forms_id ="+formId+" ";
		autoFormDao.executeSql(auToFormFieldSql);
	}

	
	public String queryNo(String auToFormNewId) {
		return autoFormDao.queryNo(auToFormNewId);
	}
	
	public void updateFlowDetailed(String flowTaskId, String statusbeforeid,
			String statusbefore, String statusafterid, String statusafter,String nextUserId,String nextRoleId) {
		HttpServletRequest request = ServletActionContext.getRequest();
		//流程下一步节点
		String userId = ServletActionContext.getRequest().getSession().getAttribute("TDM_USER_ID").toString();
		String userNm = ServletActionContext.getRequest().getSession().getAttribute("username").toString();
		FlowTask flowTask = autoFormDao.getFlowTaskById(Long.parseLong(flowTaskId));
		//操作明细对象
		FlowDetailed flowDetailed = new FlowDetailed();
		flowDetailed.setFlowTaskId(flowTask.getId());
		flowDetailed.setOperatorperson(userNm);
		flowDetailed.setOperatortime(new Timestamp(System.currentTimeMillis()));
		flowDetailed.setStatusbefore(statusbefore);
		flowDetailed.setStatusbeforeid(statusbeforeid);
		flowDetailed.setStatusafter(statusafter);
		flowDetailed.setStatusafterid(statusafterid);
		flowDetailed.setActiontype("流程操作");
		flowDetailed.setFlowTypeId(flowTask.getFlowTypeId());
		flowDetailed.setOperatorpersonId(Long.parseLong(userId));
		if(null!=flowTask.getNextRolesId() && !"".equals(flowTask.getNextRolesId())){
			flowDetailed.setNextRoleId(nextRoleId);
		}
		if(null!=flowTask.getNextUsersId()&&!"".equals(flowTask.getNextUsersId())){
			flowDetailed.setNextUserId(nextUserId);
		}
		autoFormDao.saveFlowDetailed(flowDetailed);
	}

    
	public String saveFlowTask(FlowTask flowTask1) {
		return autoFormDao.saveFlowTask(flowTask1);
	}

	
	public void saveFlowDetailed(FlowDetailed flowDetailed) {
		autoFormDao.saveFlowDetailed(flowDetailed);
	}
	
	
	public void saveCustomNo(TdmCustomNo tcn) {
		autoFormDao.saveCustomNo(tcn);
	}
	
	
	public PageResult queryCustomNoList(Map<String, String> filterMap) {
		return autoFormDao.queryCustomNoList(filterMap);
	}
	
	
	public String queryCunstomNumber(String custonNumber,Long customId) {
		TdmCustomNo tdmCustomNo = autoFormDao.queryTdmCustomNoById(customId);
		//当前值
		Long dangqianBianhao = tdmCustomNo.getCurNumber();
		
		String customNumberNo = "";//最终的编号
		//例如 agm[YYYY][XXXX]  agm为头，[YYYY]为中，[XXXX]为尾
		String startStr = "";//头字符串
		String middenStr = "";//中间字符串
		String middenStr1 = "";//中间字符串([MM])
		String endStr = "";//尾字符串
		
		Calendar cal=Calendar.getInstance();   
		
		startStr = custonNumber.substring(0,custonNumber.indexOf("[Y") + 2);
		//生成中间字符串yyyymmdd
		if(custonNumber.indexOf("[YYYY]")>=0){
			middenStr = String.valueOf(cal.get(Calendar.YEAR));    
		}
		if(custonNumber.indexOf("[YY]")>=0){
			String year = String.valueOf(cal.get(Calendar.YEAR));
			middenStr = year.substring(year.length()-2);
		}
		if(custonNumber.indexOf("[MM]")>=0){
			String month = String.valueOf(cal.get(Calendar.MONTH)+1);
			String monthnew = "0"+month;
			middenStr1 = monthnew.substring(monthnew.length()-2);
		}
		if(custonNumber.indexOf("[YYMM]")>=0){
			String year = String.valueOf(cal.get(Calendar.YEAR));
			year = year.substring(year.length()-2);
			String month = String.valueOf(cal.get(Calendar.MONTH)+1);
			String monthnew = "0"+month;
			middenStr = year+monthnew.substring(monthnew.length()-2);
		}
		if(custonNumber.indexOf("[YYYYMM]")>=0){
			String year = String.valueOf(cal.get(Calendar.YEAR));
			String month = String.valueOf(cal.get(Calendar.MONTH)+1);
			String monthnew = "0"+month;
			middenStr = year+monthnew.substring(monthnew.length()-2);
		}
		if(custonNumber.indexOf("[YYYYMMDD]")>=0){
			String year = String.valueOf(cal.get(Calendar.YEAR));
			String month = String.valueOf(cal.get(Calendar.MONTH)+1);
			String monthnew = "0"+month;
			String date = String.valueOf(cal.get(Calendar.DATE));
			String dateNew = "0"+date;
			middenStr = year + monthnew.substring(monthnew.length()-2) + dateNew.substring(dateNew.length()-2);
		}
		String xxxLengthOld = custonNumber.substring(custonNumber.indexOf("[X"),custonNumber.indexOf("X]") +2);
		//拼接数字编号(最多10位)
		String xxxLength = custonNumber.substring(custonNumber.indexOf("[X") + 1,custonNumber.indexOf("X]") + 1 );
		String xxxNumber = "0000000000"+dangqianBianhao.toString();
		endStr = xxxNumber.substring(xxxNumber.length() - xxxLength.length());
		if(custonNumber.indexOf("[YYYY]")>=0){
			custonNumber = custonNumber.replace("[YYYY]", middenStr);
		}
		if(custonNumber.indexOf("[YY]")>=0){
			custonNumber = custonNumber.replace("[YY]", middenStr);
		}
		if(custonNumber.indexOf("[MM]")>=0){
			custonNumber = custonNumber.replace("[MM]", middenStr1);
		}
		if(custonNumber.indexOf("[YYMM]")>=0){
			custonNumber = custonNumber.replace("[YYMM]", middenStr);
		}
		if(custonNumber.indexOf("[YYYYMM]")>=0){
			custonNumber = custonNumber.replace("[YYYYMM]", middenStr);
		}
		if(custonNumber.indexOf("[YYYYMMDD]")>=0){
			custonNumber = custonNumber.replace("[YYYYMMDD]", middenStr);
		}
		
		custonNumber = custonNumber.replace(xxxLengthOld, endStr);
		dangqianBianhao = dangqianBianhao + 1l;
		tdmCustomNo.setCurNumber(dangqianBianhao);
		autoFormDao.updateCustom(tdmCustomNo);
		return custonNumber;
	}

	

	
	public List findAllBySql(String typeSql) {
		return autoFormDao.findAllBySql(typeSql);
	}

	
	public String queryTdmItem(String taskId) {
		return autoFormDao.queryTdmItem(taskId);
	}

	
	public IAutoDao getAutoDao() {
		return autoDao;
	}

	public void setAutoDao(IAutoDao autoDao) {
		this.autoDao = autoDao;
	}

	
	public TdmCustomNo goUpdateCustomNumber(String id) {
		return autoDao.goUpdateCustomNumber(id);
	}

	
	public void updateCustomNo(TdmCustomNo tcn) {
		  autoFormDao.updateCustomNo(tcn);
	}

	
	public TdmCustomNo queryTdmCustomNo(long id) {
		// TODO Auto-generated method stub
		return autoFormDao.queryTdmCustomNo(id);
	}
	public void savePriority(String ids, String formid) {
		autoFormDao.savePriority(ids, formid);
	}

	
	public List queryBySql(String sql) {
		return autoFormDao.queryBySql(sql);
	}

	
	public void executeBySql(String sql) {
		autoFormDao.executeBySql(sql);
	}
	
}
